import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;



class  Resource{
    AtomicInteger num= new AtomicInteger(1);
    volatile  int state=1;

    ReentrantLock lock=new ReentrantLock();
    //
    Condition c1= lock.newCondition();
    Condition c2= lock.newCondition();


    void print1() throws Exception{
        lock.lock();
        while(state!=1){
            c1.await();
        }
        System.out.println(Thread.currentThread().getName()+num);
        num.getAndIncrement();
        state=2;
        c2.signal();
        lock.unlock();
    }

    void print2() throws Exception{
        lock.lock();
        while(state!=2){
            c2.await();
        }
        System.out.println(Thread.currentThread().getName()+num);
        num.getAndIncrement();
        state=1;
        c1.signal();
        lock.unlock();
    }


}

public class AlternatePrint {


    public static void main(String[] args) {

        Resource resource=new Resource();
        new  Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    resource.print1();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }


        },"A").start();

        new  Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    resource.print2();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        },"B").start();
    }

}
